package com.pengtu.gsj.dao.hibernate;

import java.util.Map;

import javax.annotation.PostConstruct;

import org.hibernate.SessionFactory;
import org.hibernate.event.service.spi.EventListenerRegistry;
import org.hibernate.event.spi.EventType;
import org.hibernate.internal.SessionFactoryImpl;
import org.springframework.util.Assert;

/**
 * @author zl
 * @version 创建时间：2017年3月30日 上午11:02:33 类说明
 */
public class HibernateEventWiring {

	private SessionFactory sessionFactory;

	private Map<String, Object> listeners;

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@PostConstruct
	private  void registerListeners() {
		Assert.notNull(sessionFactory);
		EventListenerRegistry eventListenerRegistry = ((SessionFactoryImpl) sessionFactory)
				.getServiceRegistry().getService(EventListenerRegistry.class);
		for (String key : listeners.keySet()) {
		
			EventType eventType = EventType.resolveEventTypeByName(key);
			eventListenerRegistry.getEventListenerGroup(eventType).prependListener(listeners.get(key));
		}
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	public void setListeners(Map<String, Object> listeners) {
		this.listeners = listeners;
	}

}
